JS | 您所在的位置:网站首页 › Input file读取上传文件 › JS |
在另一篇里已经说了如何实现type="file"的input文件上传,现新增需求需要展示上传的进度,所以在原来基础上再加上 文件上传-不带进度条: https:////www.cnblogs.com/liangpi/p/12503533.html 先看效果展示:
1、首先还是先添加html 上传附件 0%2、css样式 .fileBtn { position:relative; } .fileBtn #uploadfile { width: 120px; height: 30px; filter: Alpha(opacity=0); -moz-opacity:0; opacity: 0; position: absolute; z-index: 2; } .fileBtn .btn-flie { width: 120px; height: 30px; position: absolute; z-index: 1; } .info-item { margin-top: 30px; } .progressBox{ margin-top: 35px; width: 50%; height: 10px; background: #fff; display: block; } .progressBox .progressItem { width: 100%; height: 100%; border: 1px solid #ccc; border-radius: 5px; position: relative; } .progressBox .progressBar{ width: 0; height: 100%; background: #337ab7; border-radius: 5px; position: absolute; top: 0; left: 0; } .progressBox .progressText{ font-size: 14px; color: #337ab7; position: absolute; top: -7px; right: -50px; }3、js相关代码 var fileList = [] // 文件list $('#uploadfile').change(function(){ // 初始化进度条状态 // $('#progressBox').css("display","block") $('#progressBar').css('width','0%'); $('#progressText').text('0%'); var fileItem = $('#uploadfile')[0].files[0] var formData = new FormData(); formData.append('file', fileItem) formData.append('type', '1') $.ajax ({ type : "post", url : "/user/upload", data : formData, async : true, cache : false, contentType : false,//需设置为false,因为是FormData对象,且已经声明了属性enctype="multipart/form-data" processData : false,//需设置为false,因为data值是FormData对象,不需要对数据做处理 dataType : 'json', xhr: function() { var xhr = $.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.addEventListener("progress", function (e) { var loaded = e.loaded; //已经上传大小情况 var tot = e.total; //附件总大小 var per = Math.floor(100 * loaded / tot); //已经上传的百分比 $('#progressBar').css('width',per+'%'); //这里指的是进度条的宽度等于完成的百分比 $('#progressText').text(per+'%'); //显示进度百分比 }, false); return xhr; } }, success : function (data) { if (data.code == 2000){ var dataInfo = data.data if(dataInfo) { toastr.success('上传成功'); // 提示上传成功插件-可以更换与不用 // $('#progressBox').css("display","none") // 这句是上传成功后将进度条隐藏,看自己需求是否需要 // 重置进度条 $('#progressBar').css('width','0%'); $('#progressText').text('0%'); setTimeout( function(){ toastr.clear(); }, 1000); fileList.push(dataInfo) showFile() } } else{ alert(data.message); } }, error : function(data) { toastr.error('上传失败'); // $('#progressBox').css("display","none") setTimeout( function(){ toastr.clear(); }, 1000); } }); }); function showFile() { // 展示文件信息 var fileItem = fileList if(fileItem.length){ var str = '' for(var i = 0; i < fileItem.length; i++){ str += ''; str += fileItem[i].name str += '' str += '' str += '" ; if(status!="1&&status!=3){" str +="" ; } str + ; str + ; } $('#fileList').html(str) } else { $('#fileList').empty() } };
|
CopyRight 2018-2019 实验室设备网 版权所有 |